<?php
/**
 * Created by PhpStorm.
 * User: LiuPeng
 * Date: 2018/4/4
 * Time: 14:38
 */

class doumiAPI {

    const URL_GET_ACCESS_TOKEN = '/oauth/access_token';
    const URL_BASIC_LIST = '/basic/list';
    const URL_BASIC_DETAIL = '/basic/detail';
    const URL_BASIC_REGISTER = '/basic/register';
    const URL_BASIC_APPLY = '/basic/apply';
    const URL_APPLY = '/apply';

    const URL_ASO_STATUS = '/idfa/status';
    const URL_ASO_CLICK = '/idfa/click';

    /*const API_ROOT = 'http://open-test.doumi.com';
    private $client_id = '35c9fed7-7858-4867-b220-c82b09af629b';
    private $client_secret = 'llPHZmZRTI0R4fOSvRm4oO5TVjBYgZxCpsiuirk9';*/

    const API_ROOT = 'http://open.doumi.com';
    private $client_id = 'f0c2e2dc-7c31-4605-917a-522cff0ce5d0';
    private $client_secret = 'FrrQyIAGPsAnYpVKWJ4zd6v5je3SGxHzqOndh2r8';

    private $access_token;
    private $token_type;
    private $error;
    private $error_description;

    public function __construct($options = array()) {
        if (isset($options['client_id'])) {
            $this->client_id = $options['client_id'];
        }
        if (isset($options['client_secret'])) {
            $this->client_secret = $options['client_secret'];
        }
    }

    private function setCache($cachename, $value, $expired) {
        return memory('set', $cachename, $value, $expired);
    }

    private function getCache($cachename) {
        return memory('get', $cachename);
    }

    private function removeCache($cachename) {
        return memory('delete', $cachename);
    }

    private function get_access_token() {
        $authname = 'doumi_access_token_' . $this->client_id;
        if ($rs = $this->getCache($authname)) {
            $this->access_token = $rs['access_token'];
            $this->token_type = $rs['token_type'];
            return $rs;
        }
        $result = $this->getOauthAccessToken();
        if ($result) {
            $arr = json_decode($result, true);
            if (!$arr || !empty($arr['error'])) {
                $this->error = $arr['error'];
                $this->error_description = $arr['error_description'];
                return false;
            }

            $this->access_token = $arr['access_token'];
            $this->token_type = $arr['token_type'];
            $expire = $arr['expires_in'] ? (intval($arr['expires_in']) - 100) : 3600;
            unset($arr['expires_in']);
            $this->setCache($authname, $arr, $expire);

            return $arr;
        }

        return false;
    }

    private function getOauthAccessToken() {
        $url = self::API_ROOT . self::URL_GET_ACCESS_TOKEN;
        $oCurl = curl_init();
        $headers = array("Content-Type: application/json", "Accept: application/vnd.doumi.v1+json");
        $param = json_encode(
            array(
                'grant_type' => 'client_credentials',
                'client_id' => $this->client_id,
                'client_secret' => $this->client_secret,
                'scope' => 'basic'
            )
        );

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);

        $sContent = curl_exec($oCurl);
        //logResult('curl_access_token', $sContent);

        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    public function basic_list($option) {
        if (empty($option)) return false;
        $param = array();
        if (isset($option['domain'])) $param['domain'] = $option['domain']; // bj(北京)、sh(上海)
        if (isset($option['category'])) $param['category'] = $option['category']; // y(每日结算)、c(有提成)、j(斗米担保)、w(会员有奖)；使用示例:category=cw，默认为所有工作性质
        if (isset($option['jobtype'])) $param['jobtype'] = $option['jobtype']; // chuandan(传单派发)、daogou(促销导购)
        if (isset($option['sort'])) $param['sort'] = $option['sort']; // 1(默认推荐排序)、2(最新发布)、3(薪资最高)

        $param = http_build_query($param);

        $result = $this->post(
            self::API_ROOT . self::URL_BASIC_LIST,
            $param
        );

        return $result;
        /*
        {
          "code": 0,
          "message": "Success.",
          "data": [
            {
              "id": 4037500,
              "title": "发一个直聘测一下补贴016",
              "company": "一家生产葫芦娃的公司",
              "date": "20180412~20180531",
              "salary": 100,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153686,
              "title": "批量报名数据",
              "company": "测试普通职位账号",
              "date": "20180509~20190509",
              "salary": 3300,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153671,
              "title": "世纪婚礼强东奶茶妹妹新婚大典",
              "company": "斗米河神科技公司",
              "date": "20180509~20180531",
              "salary": 500,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153670,
              "title": "详情页面改版",
              "company": "公司名称123",
              "date": "20180508~20180522",
              "salary": 1,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153666,
              "title": "投诉职位其他2",
              "company": "爱工作",
              "date": "20180413~20180531",
              "salary": 1,
              "salary_unit_str": "元/件"
            },
            {
              "id": 4153308,
              "title": "jjl_second_time",
              "company": "jjl测试环境有限公司",
              "date": "20180502~20190502",
              "salary": 101,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153310,
              "title": "APP发布全职贴",
              "company": "阿里巴巴集团",
              "date": "20180502~20190502",
              "salary": 15364,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153309,
              "title": "jjl招聘保安",
              "company": "jjl测试环境有限公司",
              "date": "20180502~20180630",
              "salary": 500,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153306,
              "title": "微信埋点微信埋点",
              "company": "北京周很快就到有限公司",
              "date": "20180502~20190502",
              "salary": 3221,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153300,
              "title": "jjl_first全职招聘",
              "company": "jjl测试环境有限公司",
              "date": "20180502~20190502",
              "salary": 20000,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153296,
              "title": "埋点面试地址",
              "company": "北京周很快就到有限公司",
              "date": "20180517~20180630",
              "salary": 155,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153295,
              "title": "BD发布全职普帖1",
              "company": "测试普通职位账号",
              "date": "20180502~20190502",
              "salary": 3300,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153294,
              "title": "商家发布全职普帖1",
              "company": "测试普通职位账号",
              "date": "20180502~20190502",
              "salary": 3300,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153287,
              "title": "BD发布全职普帖",
              "company": "测试普通职位账号",
              "date": "20180502~20190502",
              "salary": 3300,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153286,
              "title": "商家发布全职普帖",
              "company": "测试普通职位账号",
              "date": "20180502~20190502",
              "salary": 3300,
              "salary_unit_str": "元/月"
            },
            {
              "id": 4153285,
              "title": "BD代发APP试玩",
              "company": "测试普通职位账号",
              "date": "0~0",
              "salary": 100,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153284,
              "title": "BD代发铂金",
              "company": "测试普通职位账号",
              "date": "20180709~20180719",
              "salary": 100,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153276,
              "title": "西二旗卖报纸-复制APP试玩",
              "company": "滴滴",
              "date": "0~0",
              "salary": 5000,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153269,
              "title": "思思思思思思思思is",
              "company": "斗米兼职有限公司",
              "date": "20180428~20180531",
              "salary": 11,
              "salary_unit_str": "元/天"
            },
            {
              "id": 4153261,
              "title": "滴滴外卖送餐员",
              "company": "yj牛肉有限公司1",
              "date": "20180501~20180531",
              "salary": 200,
              "salary_unit_str": "元/天"
            }
          ]
        }
    */
    }

    public function basic_detail($option) {
        if (empty($option)) return false;

        $id = $option['id'];
        $result = $this->post(
            self::API_ROOT . self::URL_BASIC_DETAIL . '/' . $id
        );

        return $result;
        /*
        {
          "code": 0,
          "message": "Success.",
          "data": {
            "id": "4153194",
            "title": "上海淘宝客职位",
            "company": "yj牛肉有限公司1",
            "date": "20180425~20181231",
            "city": "上海",
            "salary": 11,
            "salary_unit_str": "元/天",
            "payment_type_str": "日结",
            "hire_number": "12",
            "description": "上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位上海淘宝客职位",
            "address_list": [
              {
                "id": "116787",
                "city": "上海",
                "district": "长宁",
                "street": "中山公园",
                "address": "中山公园-地铁站",
                "addr_type": "0"
              }
            ],
            "interview_addresss": {
              "1": {
                "id": "116788",
                "city": "上海",
                "district": "浦东",
                "street": "东昌站地铁",
                "address": "上海市东方医院",
                "addr_type": "1"
              }
            }
          }
        }
    */
    }

    public function basic_register($option) {
        if (empty($option)) return false;
        $param = array();
        if (isset($option['mobile'])) $param['mobile'] = $option['mobile']; // 手机号
        if (isset($option['name'])) $param['name'] = $option['name']; // 姓名（限制16个字符内）
        if (isset($option['birth'])) $param['birth'] = $option['birth']; // 生日（例如：1990-03）
        if (isset($option['sex'])) $param['sex'] = $option['sex']; // 性别，1(男)、2(女)
        if (isset($option['is_student'])) $param['is_student'] = $option['is_student']; // 是否学生，0(否)、1(是)
        if (isset($option['height'])) $param['height'] = $option['height']; // 身高(例如：168)
        if (isset($option['school_name'])) $param['school_name'] = $option['school_name']; // 学校名字（限制30个字符内）
        if (isset($option['degree'])) $param['degree'] = $option['degree']; // 学历，0(初中以下)、1(高中)、2(大专)、3(本科)、4(硕士)、5(博士及以上)、6(初中)
        if (isset($option['enrol_date'])) $param['enrol_date'] = $option['enrol_date']; // 入学年月（例如：200806）

        $param = http_build_query($param);

        $result = $this->post(
            self::API_ROOT . self::URL_BASIC_REGISTER,
            $param
        );

        return $result;
        /*
            {
              "code": 0,
              "message": "Success.",
              "data": {
                "certificate": "c2eb68ca0f4b7da238497e107a89961d",
                "expires_in": 86400
              }
            }
        */
    }

    public function basic_apply($option) {
        if (empty($option)) return false;
        $param = array();
        if (isset($option['certificate'])) $param['certificate'] = $option['certificate']; // 临时身份凭据
        if (isset($option['post_id'])) $param['post_id'] = $option['post_id']; // 职位id（斗米平台内的职位体系）
        if (isset($option['address_id'])) $param['address_id'] = $option['address_id']; // 上班位置关联id

        $param = http_build_query($param);

        $result = $this->post(
            self::API_ROOT . self::URL_BASIC_APPLY,
            $param
        );

        return $result;
        /*
            {
              "code": 0,
              "message": "Success."
            }
        */
    }

    public function apply() {

    }

    public function aso_status() {

    }

    public function aso_click() {

    }

    // 输入参数类型为application/x-www-form-urlencoded，返回数据类型为json
    private function post($url, $param = false) {
        $rs = $this->get_access_token();
        if (!$rs) return false;

        $oCurl = curl_init();
        $headers = array(
            "Content-type: application/x-www-form-urlencoded",
            "Authorization: " . $rs['token_type'] . " " . $rs['access_token']
        );
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        if ($param) {
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, $param);
        }
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);

        $sContent = curl_exec($oCurl);
        //logResult('curl', $sContent);

        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    // 输入参数类型为application/json，返回数据类型为json
    private function post_json($url, $param = false) {
        $rs = $this->get_access_token();
        if (!$rs) return false;

        $oCurl = curl_init();
        $headers = array(
            "Content-type: application/json",
            "Accept: application/vnd.doumi.v1+json",
            "Authorization: " . $rs['token_type'] . " " . $rs['access_token']
        );
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        if ($param) {
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, $param);
        }
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}